import json
import time

from credit_voice_service.dialogue.entity import dialogue_session_entity as dialogue_entity
from credit_voice_service.dialogue.util import request_util
from credit_voice_service.settings import log, TRANSFER_URL


# 请求DS评分卡
def judgeTransfer(answer, dialogue_session, company_id):
    start_time = time.time()
    # dialogue_entity.setReply(answer, dialogue_session)
    payload = {"context": json.dumps(dialogue_session, ensure_ascii=False),
               "companyId": company_id,
               "modelId": 0}
    log.info("[judgeTransfer] =======开始调用评分模型，session_id:{},companyId:{}========".format(dialogue_session["sessionId"], company_id))
    result = request_util.post(TRANSFER_URL, payload, timeout=5)
    if result is not None and "sign" in result:
        result = result.encode('utf-8').decode('unicode_escape')
        result = json.loads(result)
    else:
        log.info("[judgeTransfer] 报错 result:{}".format(result))
        result = None
    log.info("[judgeTransfer] 评分模型耗时:{:.2f}ms,\n result:{}".format((time.time()-start_time)*1000, result))
    return result


if __name__ == '__main__':
    dialogueSession = {
        "sessionId": "0-2120-581717275-1679689883418828800-21",
        "workspaceId": 661490,
        "userInfo": {
            "sessionId": "0-2120-581717275-1679689883418828800-21",
            "workspaceId": 661490,
            "userId": "0-2120-581717275-1679689883418828800-21",
            "dialogueId": 1083291,
            "intentId": 1083292
        },
        "dialogueHistory": {
            "dialogueItemList": [{
                "workspaceId": 661490,
                "query": "",
                "reply": "[京东养老金带操作B版-0706]@#开场-李先生||喂，您好~请问您是李先生吗？#@",
                "replyTime": "2023-07-13 20:05:55.110",
                "queryTime": ""
            }, {
                "workspaceId": 661490,
                "query": "是的",
                "reply": "[坐席询问用户:是否打开APP-用户肯定]@#JD1001-1C||京东金融APP打#@",
                "replyTime": "2023-07-13 20:05:55.110",
                "queryTime": ""
            }]
        },
        "dialogueLLM": [
            {'role': 'assistant', 'content': "[坐席询问用户:是否打开APP-用户肯定]@#JD1001-1C||京东金融APP打#@",},
            {'role': 'user', 'content': '是的'}
        ]
    }
    replyBean = {
        "query": "是的",
        "answer": "[坐席询问用户:是否打开APP-用户肯定]@#JD1001-1C||京东金融APP打开之后#@"
    }
    companyId = 2239
    transfer = judgeTransfer(replyBean, dialogueSession, companyId)
    print(str(transfer.get("sign")))
    if transfer is not None and "sign" in transfer and transfer["sign"] == 1:
        enen = transfer["sign"]
    pass
